package com.itrip.service.impl;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.itrip.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SmsServiceimpl implements SmsService {
    @Value("${sms.server.ip}")
    private String serverIp;
    @Value("${sms.server.port}")
    private String serverPort;
    @Value("${sms.account.sId}")
    private String accountSId;
    @Value("${sms.account.token}")
    private String accountToken;
    @Value("${sms.app.id}")
    private String appId;
    @Value("${sms.app.templateid}")
    private String templateId;

    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean sendSms(String phone, String code, int minute) {

        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String[] datas = {code,String.valueOf(minute)};
        HashMap<String, Object> result = sdk.sendTemplateSMS(phone,templateId,datas);
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for(String key:keySet){
                Object object = data.get(key);
                log.debug("发送短信返回消息:"+key +" = "+object);
            }
            //手机号key，密码做value,minute多少分钟失效
            redisTemplate.opsForValue().set(phone,code,minute,TimeUnit.MINUTES);
            return true;
        }else{
            //异常返回输出错误码和错误信息
                log.error("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
        }
        return false;
    }

    @Override
    public boolean validate(String phone, String code) {
        String reidsCode =(String)redisTemplate.opsForValue().get(phone);
        if(reidsCode !=null && reidsCode.equals(code)){
              //说明存在
            redisTemplate.delete(phone);
            return true;
        }
        return false;
    }
}
